﻿using SmartSpace.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SmartSpace.OA
{
    public partial class OAService : IOAService
    {
        public ServiceResult ClockIn(string account, DateTime datetime)
        {
            using (OADbContext context = new OADbContext())
            {
                AttendanceRecord record = context.AttendanceRecordSet.Where(p => p.Account == account && p.Year == datetime.Year && p.Month == datetime.Month && p.Day == datetime.Day)
                    .SingleOrDefault();
                if (record == null)
                {
                    record = new AttendanceRecord();
                    record.Id = Guid.NewGuid();
                    record.Account = account;
                    record.Year = datetime.Year;
                    record.Month = datetime.Month;
                    record.Day = datetime.Day;
                    record.InTime = datetime;
                    EntityRepository.Save(record, context);
                    return new ServiceResult(EntityRepository.Commit(context));
                }
                else
                {
                    return new ServiceResult(false);
                }
            }
        }

        public ServiceResult ClockOut(string account, DateTime datetime)
        {
            using (OADbContext context = new OADbContext())
            {
                AttendanceRecord record = context.AttendanceRecordSet.Where(p => p.Account == account && p.Year == datetime.Year && p.Month == datetime.Month && p.Day == datetime.Day)
                    .SingleOrDefault();
                if (record == null)
                {
                    record = new AttendanceRecord();
                    record.Id = Guid.NewGuid();
                    record.Account = account;
                    record.Year = datetime.Year;
                    record.Month = datetime.Month;
                    record.Day = datetime.Day;
                    record.OutTime = datetime;
                    EntityRepository.Save(record, context);
                    return new ServiceResult(EntityRepository.Commit(context));
                }
                else
                {
                    record.OutTime = datetime;
                    EntityRepository.Save(record, context);
                    return new ServiceResult(EntityRepository.Commit(context));
                }
            }
        }

        public AttendanceRecord GetAttendanceRecord(string account, int year, int month, int day)
        {
            using (OADbContext context = new OADbContext())
            {
                return context.AttendanceRecordSet.Where(p => p.Account == account && p.Year == year && p.Month == month && p.Day == day)
                    .SingleOrDefault();
            }
        }
    }
}
